package org.wangnian.validationdemo.exception;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    public Map<String,Object> handleConstraintViolationException(ConstraintViolationException e){
        Map<String, Object> map = new HashMap<>();
        String msg = new ArrayList<>(e.getConstraintViolations()).get(0).getMessage();
        map.put("status",400);
        map.put("msg",msg);
        return map;
    }

    @ExceptionHandler(BindException.class)
    public Map<String,Object> handleBindException(BindException e){
        Map<String, Object> map = new HashMap<>();
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        map.put("status",400);
        map.put("msg",msg);
        return map;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String,Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        Map<String, Object> map = new HashMap<>();
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        map.put("status",400);
        map.put("msg",msg);
        return map;
    }

}
